package com.fate.securecheckplatform.ui.frags;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fate.securecheckplatform.R;
import com.fate.securecheckplatform.adapters.RegisterAdapter;
import com.fate.securecheckplatform.base.BaseFragment;
import com.fate.securecheckplatform.bean.EventEntity;
import com.fate.securecheckplatform.bean.TableForbiddenPerformance;
import com.fate.securecheckplatform.constant.Constant;
import com.fate.securecheckplatform.db.DataBase;
import com.fate.securecheckplatform.ui.acts.AddRegisterActivity;
import com.fate.securecheckplatform.utils.ExecutorManager;
import com.fate.securecheckplatform.utils.ToastUtil;
import com.fate.securecheckplatform.utils.Util;
import com.fate.securecheckplatform.views.RecyclerViewDivider;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author:   RandBII
 * DATE:   2020/1/8
 * Description: 登记
 */
public class RegisterFragment extends BaseFragment {

    private static final String TAG = "RegisterFragment";
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    @BindView(R.id.rv)
    RecyclerView mRv;
    List<TableForbiddenPerformance> datas = new ArrayList<>();
    private RegisterAdapter adapter;
    private int page = 1;
    private int pageSize = 15;
    private int totalCount = 0;
    private DataBase dataBase;
    private int selecteItemPosition = -1;

    public static RegisterFragment get() {
        RegisterFragment fragment = new RegisterFragment();
        Bundle bundle = new Bundle();
        bundle.putString("name", TAG);
        fragment.setArguments(bundle);
        return fragment;
    }

    private void ObtainFragment() {

    }

    @Override
    protected void initData() {

        Future<Integer> count = ExecutorManager.getService().submit(() -> dataBase.forbiddenObjectDao().getPerformancesCount());

        try {
            if (count.get() == null) {
                totalCount = 0;
            } else {
                totalCount = count.get();
            }
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }

    }

    private void loadData() {
        Future<List<TableForbiddenPerformance>> future = ExecutorManager.getService().submit(() ->
                dataBase.forbiddenObjectDao().getNotOutPerformances(Util.getPageStartCount(page, pageSize), pageSize));

        try {
            List<TableForbiddenPerformance> newPerformances = future.get();
//            Log.e("nature--->","--null");
            if (newPerformances != null) {
//                Log.e("nature--->","--not null");
                selecteItemPosition = -1;
                if (page == 1) {
                    datas.clear();
                }
                datas.addAll(newPerformances);
                if (selecteItemPosition != -1 && selecteItemPosition < datas.size() - 1) {
                    datas.get(selecteItemPosition).setAndroidSelected(true);
                }
                adapter.notifyDataSetChanged();
            }
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initView(View root) {
        dataBase = DataBase.getInstance(getActivity());
        EventBus.getDefault().register(this);
        datas = new ArrayList<>();
        mRv.setHasFixedSize(true);
        mRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new RegisterAdapter(getActivity(), datas);
        mRv.setAdapter(adapter);
        RecyclerViewDivider divider = new RecyclerViewDivider(getActivity());
        divider.setShowLastDivider(true);
        mRv.addItemDecoration(divider);
        mSrl.setOnRefreshListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                if (!canLoadMore()) {
                    return;
                }
                page++;
                loadData();
                if (mSrl != null) {
                    mSrl.finishLoadMore();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                loadData();
                if (mSrl != null) {
                    mSrl.finishRefresh();
                }
            }
        });

        adapter.setOnItemClickListener((view, position) -> {

            cancelAllSelected();
            selecteItemPosition = position;
            TableForbiddenPerformance p = datas.get(position);
            p.setAndroidSelected(true);
            adapter.notifyDataSetChanged();
        });

        mSrl.autoRefresh();
    }

    /**
     * 可以加载下一页
     *
     * @return
     */
    private boolean canLoadMore() {
        if (totalCount == 0) return false;
        return (pageSize * page < totalCount);
    }

    private void cancelAllSelected() {
        if (datas != null) {
            for (TableForbiddenPerformance performance : datas) {
                performance.setAndroidSelected(false);
            }
        }
    }

    @Override
    protected int layoutResourceId() {
        return R.layout.fragment_register;
    }

    @OnClick({R.id.tv_delete, R.id.tv_edit, R.id.tv_add})
    public void onClickEvenet(View v) {
        switch (v.getId()) {
            case R.id.tv_delete:
                if (datas == null || datas.size() == 0) {
                    return;
                }
                if (selecteItemPosition == -1) {
                    ToastUtil.toast("请先选择一条信息");
                    return;
                }
                deleteOnePerformance();
                if (mSrl != null) {
                    mSrl.autoRefresh();
                }
                break;
            case R.id.tv_edit:
                if (datas == null || datas.size() == 0) {
                    return;
                }
                if (selecteItemPosition == -1) {
                    ToastUtil.toast("请先选择一条信息");
                    return;
                }
                toEditPage();

                break;
            case R.id.tv_add:

                navigateToAddNoPrams();

                break;
        }
    }

    private void toEditPage() {
        TableForbiddenPerformance performance = datas.get(selecteItemPosition);
        Intent intent = new Intent(getActivity(), AddRegisterActivity.class);
        intent.putExtra(Constant.DATA_PERFORMANCE, performance);
        startActivity(intent);
    }

    /**
     * 删除一条信息
     */
    private void deleteOnePerformance() {
        if (selecteItemPosition == -1 || selecteItemPosition > datas.size() - 1) {
            return;
        }
        TableForbiddenPerformance p = datas.get(selecteItemPosition);
        ExecutorManager.getService().submit(() -> dataBase.forbiddenObjectDao().deleteOneForbiddenPerformance(p));
        selecteItemPosition = -1;
        adapter.notifyDataSetChanged();
    }

    /**
     * 跳转添加页面
     */
    private void navigateToAddNoPrams() {
        Intent intent = new Intent(getActivity(), AddRegisterActivity.class);
        startActivity(intent);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRecieveMessage(EventEntity entity) {
        if (entity.getCode() == Constant.CODE_REFRESH_REGSITER_FRAGMENT) {
            if (mSrl != null)
                mSrl.autoRefresh();
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
